import type { StatsCard } from "../components/StatsCards.vue"
import { computed, ref } from "vue"
import * as XLSX from "xlsx"

// 邀请码接口
export interface InvitationCode {
  id: string
  code: string
  agentPath: string
  productVersion: string
  status: "used" | "pending" | "expired"
  createTime: string
  expireTime: string
  redeemPhone?: string
  redeemTime?: string
}

// 统计数据接口
export interface InvitationStats {
  total: number
  used: number
  pending: number
  expired: number
  exchangeRate: number
}

export function useInvitationManagement() {
  // 页面状态
  const loading = ref(false)
  const tableLoading = ref(false)
  const searchKeyword = ref("")
  const statusFilter = ref("all")
  const versionFilter = ref("all")

  // 弹窗状态
  const showCreateDialog = ref(false)

  // 分页状态
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)

  // 模拟邀请码数据
  const invitationCodes = ref<InvitationCode[]>([
    {
      id: "1",
      code: "PKT-STD-A1B2C3",
      agentPath: "华东区域服务商 > 上海代理商A",
      productVersion: "标准版 (398元/账号/月)",
      status: "used",
      createTime: "2024-08-01",
      expireTime: "2024-09-01",
      redeemPhone: "13800138888",
      redeemTime: "2024-08-05"
    },
    {
      id: "2",
      code: "PKT-PRO-D4E5F6",
      agentPath: "华东区域服务商 > 杭州代理商B",
      productVersion: "专业版 Pro (698元/账号/月)",
      status: "pending",
      createTime: "2024-08-02",
      expireTime: "2024-09-02"
    },
    {
      id: "3",
      code: "PKT-MAX-G7H8I9",
      agentPath: "华东区域服务商 > 上海代理商A > 浦东分销商",
      productVersion: "专业版 Pro Max (998元/账号/月)",
      status: "expired",
      createTime: "2024-07-01",
      expireTime: "2024-08-01"
    },
    {
      id: "4",
      code: "PKT-STD-X9Y8Z7",
      agentPath: "华南区域服务商 > 深圳代理商C",
      productVersion: "标准版 (398元/账号/月)",
      status: "used",
      createTime: "2024-08-03",
      expireTime: "2024-09-03",
      redeemPhone: "13900139999",
      redeemTime: "2024-08-10"
    },
    {
      id: "5",
      code: "PKT-PRO-M5N6O7",
      agentPath: "华北区域服务商 > 北京代理商D",
      productVersion: "专业版 Pro (698元/账号/月)",
      status: "pending",
      createTime: "2024-08-04",
      expireTime: "2024-09-04"
    },
    {
      id: "6",
      code: "PKT-MAX-P8Q9R0",
      agentPath: "华西区域服务商 > 成都代理商E",
      productVersion: "专业版 Pro Max (998元/账号/月)",
      status: "expired",
      createTime: "2024-07-15",
      expireTime: "2024-08-15"
    },
    {
      id: "7",
      code: "PKT-STD-S1T2U3",
      agentPath: "华东区域服务商 > 南京代理商F",
      productVersion: "标准版 (398元/账号/月)",
      status: "used",
      createTime: "2024-08-05",
      expireTime: "2024-09-05",
      redeemPhone: "13700137777",
      redeemTime: "2024-08-12"
    },
    {
      id: "8",
      code: "PKT-PRO-V4W5X6",
      agentPath: "华南区域服务商 > 广州代理商G",
      productVersion: "专业版 Pro (698元/账号/月)",
      status: "pending",
      createTime: "2024-08-06",
      expireTime: "2024-09-06"
    },
    {
      id: "9",
      code: "PKT-MAX-Y7Z8A9",
      agentPath: "华北区域服务商 > 天津代理商H",
      productVersion: "专业版 Pro Max (998元/账号/月)",
      status: "pending",
      createTime: "2024-08-07",
      expireTime: "2024-09-07"
    },
    {
      id: "10",
      code: "PKT-STD-B0C1D2",
      agentPath: "华西区域服务商 > 重庆代理商I",
      productVersion: "标准版 (398元/账号/月)",
      status: "expired",
      createTime: "2024-07-20",
      expireTime: "2024-08-20"
    },
    {
      id: "11",
      code: "PKT-PRO-E3F4G5",
      agentPath: "华东区域服务商 > 苏州代理商J",
      productVersion: "专业版 Pro (698元/账号/月)",
      status: "used",
      createTime: "2024-08-08",
      expireTime: "2024-09-08",
      redeemPhone: "13600136666",
      redeemTime: "2024-08-15"
    },
    {
      id: "12",
      code: "PKT-MAX-H6I7J8",
      agentPath: "华南区域服务商 > 佛山代理商K",
      productVersion: "专业版 Pro Max (998元/账号/月)",
      status: "pending",
      createTime: "2024-08-09",
      expireTime: "2024-09-09"
    }
  ])

  // 产品版本选项
  const productVersions = ref([
    { label: "全部版本", value: "all" },
    { label: "标准版 (398元/账号/月)", value: "standard" },
    { label: "专业版 Pro (698元/账号/月)", value: "pro" },
    { label: "专业版 Pro Max (998元/账号/月)", value: "pro_max" }
  ])

  // 状态选项
  const statusOptions = ref([
    { label: "全部状态", value: "all" },
    { label: "已兑换", value: "used" },
    { label: "待兑换", value: "pending" },
    { label: "已过期", value: "expired" }
  ])

  // 筛选后的邀请码列表（不分页，作为本地模拟数据源）
  const filteredInvitationCodes = computed(() => {
    let filtered = invitationCodes.value

    // 搜索筛选
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase()
      filtered = filtered.filter(item =>
        item.code.toLowerCase().includes(keyword)
        || item.agentPath.toLowerCase().includes(keyword)
        || (item.redeemPhone && item.redeemPhone.includes(keyword))
      )
    }

    // 状态筛选
    if (statusFilter.value !== "all") {
      filtered = filtered.filter(item => item.status === statusFilter.value)
    }

    // 版本筛选
    if (versionFilter.value !== "all") {
      const versionMap: Record<string, string> = {
        standard: "标准版",
        pro: "专业版 Pro",
        pro_max: "专业版 Pro Max"
      }
      const targetVersion = versionMap[versionFilter.value]
      if (targetVersion) {
        filtered = filtered.filter(item => item.productVersion.includes(targetVersion))
      }
    }

    // 更新总数
    total.value = filtered.length

    return filtered
  })

  // 表格当前页数据（服务端分页时由接口直接返回）
  const tableList = ref<InvitationCode[]>([])

  // 分页后的邀请码列表（本地模拟：无接口时走切片；有接口时用 tableList）
  const paginatedInvitationCodes = computed(() => {
    if (tableList.value.length > 0) return tableList.value
    const startIndex = (currentPage.value - 1) * pageSize.value
    const endIndex = startIndex + pageSize.value
    return filteredInvitationCodes.value.slice(startIndex, endIndex)
  })

  /**
   * 预留：获取邀请码表格数据（带分页）
   * 接入真实接口时，请在此处发起请求并根据返回结果：
   * - 覆盖 invitationCodes.value
   * - 覆盖 total.value（后端总条数）
   * - 可根据接口返回结构调整筛选参数
   */
  async function fetchInvitationCodes() {
    tableLoading.value = true
    try {
      // 模拟网络延迟；替换为真实 API
      await new Promise(resolve => setTimeout(resolve, 500))
      // 示例（接入时启用）：
      // const { list, totalCount } = await api.getInvitationCodes({
      //   page: currentPage.value,
      //   size: pageSize.value,
      //   keyword: searchKeyword.value,
      //   status: statusFilter.value,
      //   version: versionFilter.value,
      // })
      // tableList.value = list
      // total.value = totalCount
      // 本地模拟：用切片结果模拟表格数据与总数
      const startIndex = (currentPage.value - 1) * pageSize.value
      const endIndex = startIndex + pageSize.value
      const full = filteredInvitationCodes.value
      tableList.value = full.slice(startIndex, endIndex)
      total.value = full.length
    } finally {
      tableLoading.value = false
    }
  }

  // 统计数据
  const stats = computed<InvitationStats>(() => {
    const total = invitationCodes.value.length
    const used = invitationCodes.value.filter(item => item.status === "used").length
    const pending = invitationCodes.value.filter(item => item.status === "pending").length
    const expired = invitationCodes.value.filter(item => item.status === "expired").length
    const exchangeRate = total > 0 ? Math.round((used / total) * 100) : 0

    return {
      total,
      used,
      pending,
      expired,
      exchangeRate
    }
  })

  // 统计卡片数据（本地计算值，用于无接口时展示）
  const computedStatsCards = computed<StatsCard[]>(() => [
    {
      label: "总邀请码",
      value: stats.value.total,
      icon: "Tickets",
      iconColor: "blue"
    },
    {
      label: "已兑换",
      value: stats.value.used,
      icon: "CircleCheck",
      iconColor: "green"
    },
    {
      label: "待兑换",
      value: stats.value.pending,
      icon: "Timer",
      iconColor: "yellow"
    },
    {
      label: "已过期",
      value: stats.value.expired,
      icon: "WarningFilled",
      iconColor: "orange"
    },
    {
      label: "兑换率",
      value: stats.value.exchangeRate,
      icon: "DataAnalysis",
      iconColor: "purple",
      showPercentage: true
    }
  ])

  // 实际渲染用的卡片数据；fetchStatsCards 可覆盖
  const statsCards = ref<StatsCard[]>(computedStatsCards.value)

  // 预留：获取统计卡片数据（模拟 500ms）
  async function fetchStatsCards() {
    loading.value = true
    try {
      await new Promise(resolve => setTimeout(resolve, 500))
      // 接口返回后直接赋值：statsCards.value = resp.list
      statsCards.value = computedStatsCards.value
    } finally {
      loading.value = false
    }
  }

  // 页面头部按钮配置
  const headerButtons = ref([
    {
      text: "导出列表",
      type: "default" as const,
      icon: "Download",
      onClick: () => exportList()
    },
    {
      text: "生成邀请码",
      type: "primary" as const,
      icon: "Plus",
      onClick: () => createInvitationCode()
    }
  ])

  // 导出列表
  function exportList() {
    try {
      loading.value = true

      // 准备导出数据 - 使用当前筛选后的数据
      const exportData = filteredInvitationCodes.value.map(item => ({
        邀请码: item.code,
        归属代理: item.agentPath,
        产品版本: item.productVersion,
        状态: getStatusText(item.status),
        创建时间: item.createTime,
        有效期: item.expireTime,
        兑换手机号: item.redeemPhone || "-",
        兑换时间: item.redeemTime || "-"
      }))

      // 如果没有数据，提示用户
      if (exportData.length === 0) {
        ElMessage.warning("没有可导出的数据")
        return
      }

      // 创建工作簿
      const worksheet = XLSX.utils.json_to_sheet(exportData)
      const workbook = XLSX.utils.book_new()

      // 设置工作表名称
      XLSX.utils.book_append_sheet(workbook, worksheet, "邀请码列表")

      // 设置列宽
      const colWidths = [
        { wch: 18 }, // 邀请码
        { wch: 25 }, // 归属代理
        { wch: 20 }, // 产品版本
        { wch: 10 }, // 状态
        { wch: 12 }, // 创建时间
        { wch: 12 }, // 有效期
        { wch: 15 }, // 兑换手机号
        { wch: 12 } // 兑换时间
      ]
      worksheet["!cols"] = colWidths

      // 设置表头样式
      const headerRange = XLSX.utils.decode_range(worksheet["!ref"] || "A1")
      for (let col = headerRange.s.c; col <= headerRange.e.c; col++) {
        const cellAddress = XLSX.utils.encode_cell({ r: 0, c: col })
        if (!worksheet[cellAddress]) continue
        worksheet[cellAddress].s = {
          font: { bold: true, color: { rgb: "FFFFFF" } },
          fill: { fgColor: { rgb: "4F81BD" } },
          alignment: { horizontal: "center", vertical: "center" }
        }
      }

      // 生成文件名
      const now = new Date()
      const dateStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, "0")}${String(now.getDate()).padStart(2, "0")}`
      const timeStr = `${String(now.getHours()).padStart(2, "0")}${String(now.getMinutes()).padStart(2, "0")}`

      // 根据筛选条件生成文件名
      let fileName = `邀请码列表_${dateStr}_${timeStr}`
      if (statusFilter.value !== "all") {
        fileName += `_${getStatusText(statusFilter.value as any)}`
      }
      if (versionFilter.value !== "all") {
        const version = productVersions.value.find(v => v.value === versionFilter.value)
        fileName += `_${version?.label.split(" ")[0] || ""}`
      }
      fileName += ".xlsx"

      // 下载文件
      XLSX.writeFile(workbook, fileName)

      ElMessage.success(`导出成功！共导出 ${exportData.length} 条记录`)
    } catch (error) {
      console.error("导出失败:", error)
      ElMessage.error("导出失败，请重试")
    } finally {
      loading.value = false
    }
  }

  // 生成邀请码
  function createInvitationCode() {
    showCreateDialog.value = true
  }

  // 确认生成邀请码
  function handleCreateInvitation(data: any) {
    console.log("生成邀请码数据:", data)
    ElMessage.success("邀请码生成成功！")
    // 这里可以调用后端API生成邀请码
    // 生成成功后刷新列表
    // loadInvitationCodes()
  }

  // 复制邀请码
  function copyInvitationCode(code: string) {
    navigator.clipboard.writeText(code).then(() => {
      console.log(`邀请码 ${code} 已复制到剪贴板`)
      // 这里可以显示成功提示
    })
  }

  // 获取状态标签类型
  function getStatusTagType(status: string): "default" | "primary" | "success" | "warning" | "danger" | "info" {
    const tagTypeMap: Record<string, "default" | "primary" | "success" | "warning" | "danger" | "info"> = {
      used: "success",
      pending: "primary",
      expired: "danger"
    }
    return tagTypeMap[status] || "info"
  }

  // 获取状态文本
  function getStatusText(status: string) {
    const statusTextMap: Record<string, string> = {
      used: "已兑换",
      pending: "待兑换",
      expired: "已过期"
    }
    return statusTextMap[status] || status
  }

  // 分页切换
  function handlePageChange(page: number) {
    currentPage.value = page
    // 分页联动表格数据（服务端分页）
    fetchInvitationCodes()
  }

  // 每页大小变化
  function handleSizeChange(size: number) {
    pageSize.value = size
    currentPage.value = 1 // 重置到第一页
    // 分页大小变更联动表格数据（服务端分页）
    fetchInvitationCodes()
  }

  return {
    // 状态
    loading,
    tableLoading,
    searchKeyword,
    statusFilter,
    versionFilter,
    showCreateDialog,
    invitationCodes,
    filteredInvitationCodes,
    paginatedInvitationCodes,
    productVersions,
    statusOptions,
    stats,
    statsCards,
    headerButtons,

    // 分页状态
    currentPage,
    pageSize,
    total,

    // 方法
    exportList,
    createInvitationCode,
    copyInvitationCode,
    getStatusTagType,
    getStatusText,
    handlePageChange,
    handleSizeChange,
    handleCreateInvitation,
    fetchInvitationCodes,
    fetchStatsCards
  }
}
